import { config } from '../../config.js';
import { Common } from '../../common/common.js';
import { MyModel } from '../../../../modules/my.js';
import { config as api } from '../../../../config.js';

const app = getApp();
const my = new MyModel();
const common = new Common();

Page({
  data: {
    imageUrl: '/images/my/add_iimage.png',
    headImage: null,
    experiences: [], // 工作经历
    histories: [], // 项目经验
    educations: [], // 教育经历
    sexArray: config.data.sexArray, // 年龄模板
    experience: config.data.experience,  // 工作经验模板
    joinstauts: config.data.joinstauts, // 求职状态模板
    edu: config.data.edu, // 最高学历模板
    politics: config.data.politics, // 政治面貌模板
    name: null, // 姓名
    phone: null, // 电话号码
    sex: null,  // 性别
    birthday: null, // 出生日期
    worddate: null, // 工作经验
    jobStatus: null, // 求职状态
    maxedu: null, // 最高学历
    specialty: null, // 专业
    nativeplace: null, // 籍贯
    address: null, // 现住地址
    politic: null, // 政治面貌
    email: null, // 邮箱
    evaluation: '这个人很懒什么也没留下！', // 自我评价
    loading: false
  },
  // 上传头像
  addImage: function(e) {
    var _this = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        wx.uploadFile({
          url: api.IMAGE_URL + 'app/aliossUpload',
          header: {
            "Content-Type": "multipart/form-data"
          },
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {},
          success: result => {
            res = JSON.parse(result.data);
            if(res) {
              _this.setData({
                headImage: res.url
              })
            }else {
              wx.showToast({
                title: '上传失败,请稍后重试！',
                icon: 'none'
              })
            }
          },
          fail: err => {
            console.log('上传头像失败：', err)
          },
        });
      },
      fail: err => {
        console.log(err);
      }
    });
  },
  // 把简历存储到data中
  saveUserResume(res) {
    if (res) {
      this.setData({
        headImage: res['heardImage'],
        name: res['name'],
        phone: res['telphone'],
        sex: res['sex'],
        birthday: res['birthday'],
        worddate: res['workAge'],
        jobStatus: res['jobStatus'],
        maxedu: res['education'],
        specialty: res['specialty'],
        nativeplace: res['nativePlace'],
        address: res['hopeWorkAddress'],
        politic: res['politicsStatus'],
        email: res['email'],
        evaluation: res['selfDesc'],
        experiences: res['experiences'],
        histories: res['histories'],
        educations: res['educations'],
        loading: true
      })
    }else {
      this.setData({
        loading: true
      })
    }
  },
  // 保存修改后的简历
  saveResume(e) {
    let res = e.detail.value;
    if (res) {
      let data = {
        rid: common.getRid(),
        heardImage: this.data.headImage,
        name: res.name,
        sex: this.data.sex,
        telphone: res.phone,
        birthday: this.data.birthday,
        workAge: this.data.worddate,
        jobStatus: this.data.jobStatus,
        education: this.data.maxedu,
        specialty: res.specialty,
        nativePlace: res.nativeplace,
        hopeWorkAddress: res.address,
        politicsStatus: this.data.politic,
        email: res.email,
        selfDesc: res.evaluation
      };
      // 验证是否填写
      if(data['name'] == null || data['name'].trim() == '') {
        wx.showToast({
          title: '姓名不能为空',
          icon: 'none'
        });
        return false
      }else if(data['telphone'] == null || data['telphone'].trim() == '') {
        wx.showToast({
          title: '手机号不能为空',
          icon: 'none'
        });
        return false
      }else if(data['sex'] == null) {
        wx.showToast({
          title: '性别不能为空',
          icon: 'none'
        });
        return false
      }else if(data['birthday'] == null) {
        wx.showToast({
          title: '出生日期不能为空',
          icon: 'none'
        });
        return false
      }else if(data['workAge'] == null) {
        wx.showToast({
          title: '工作经验不能为空',
          icon: 'none'
        });
        return false
      }else if(data['jobStatus'] == null) {
        wx.showToast({
          title: '求职状态不能为空',
          icon: 'none'
        });
        return false
      }else if(data['education'] == null) {
        wx.showToast({
          title: '学历不能为空',
          icon: 'none'
        });
        return false
      }else if(data['specialty'] == null || data['specialty'].trim() == '') {
        wx.showToast({
          title: '专业不能为空',
          icon: 'none'
        });
        return false
      }else if(data['nativePlace'] == null || data['nativePlace'].trim() == '') {
        wx.showToast({
          title: '籍贯不能为空',
          icon: 'none'
        });
        return false
      }else if(data['hopeWorkAddress'] == null || data['hopeWorkAddress'].trim() == '') {
        wx.showToast({
          title: '现住地址不能为空',
          icon: 'none'
        });
        return false
      }else if(data['politicsStatus'] == null) {
        wx.showToast({
          title: '政治面貌不能为空',
          icon: 'none'
        });
        return false
      }else if(data['email'] == null || data['email'].trim() == '') {
        wx.showToast({
          title: '个人邮箱不能为空',
          icon: 'none'
        });
        return false
      }else if(data['selfDesc'] == null || data['selfDesc'].trim() == '') {
        wx.showToast({
          title: '自我评价不能为空',
          icon: 'none'
        });
        return false
      }
      if(!new RegExp(/^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g).test(data['email'])) {
        wx.showToast({
          title: '请输入正确的邮箱',
          icon: 'none'
        });
        return false
      }
      wx.getSetting({
        success: res => {
          if (!res.authSetting['scope.userInfo']) {
            app.showAuthize()
          }else {
            console.log(data);
            my.getResumes()
            .then(res => {
              if(res.data == null) {
                wx.showToast({
                  title: '修改失败，请先创建简历!',
                  icon: 'none',
                  duration: 2000
                });
              }else {
                // 更新简历
                my.updateResume(data)
                .then(res => {
                  if (res.code == 2) {
                    wx.showToast({
                      title: '修改成功',
                      icon: 'none',
                      duration: 2000
                    })
                    setTimeout(() => {
                      wx.switchTab({
                        url: '../../index/index'
                      });
                    }, 2000)
                  }else {
                    wx.showToast({
                      title: '修改失败，请稍后重试!',
                      icon: 'none',
                      duration: 2000
                    });
                  }
                })
              }
            })
          }
        }
      })
    }
  },
  // 选择事件
  bindChange: function(e) {
    let _this = this;
    switch (e.target.id) {
      // 性别
      case 'sex':
        _this.setData({
          sex: e.detail.value
        });
      break;
      // 出生日期
      case 'birthday':
        _this.setData({
          birthday: e.detail.value
        });
      break;
      // 工作经验
      case 'worddate':
        _this.setData({
          worddate: e.detail.value
        });
      break;
      // 求职状态
      case 'joinstauts':
        _this.setData({
          jobStatus: e.detail.value
        });
      break;
      // 最高学历
      case 'maxedu':
        _this.setData({
          maxedu: e.detail.value
        });
      break;
      // 政治面貌
      case 'politics':
        _this.setData({
          politic: e.detail.value
        });
      break;
      default :
      break;
    }
  },
  onLoad: function(options) {
    app.isAuthize()
    .then(res => {
      if(res) {
        my.getResumes()
        .then(res => {
          if(res.data == null) {
            wx.showToast({
              title: '请先创建简历!',
              icon: 'none',
              duration: 2000
            });
            this.setData({
              loading: true
            })
          }else {
            this.saveUserResume(res.data.resume);
          }
        })
      }else {
        this.setData({
          loading: true
        })
      }
    })
  }
})